"""
@Author    : ghenyar
@Time      : 2025/9/3 18:25
@File      : role
@Desc      : 
"""

from typing import List, Optional, Dict, Any

from pydantic import BaseModel, ConfigDict, field_validator

from app.common.tools import find_children, format_datetime
from app.models.role_model import RoleModel
from app.common.exception.exceptions import ValidationException


class RoleSchema(BaseModel):
    """数据表单验证"""
    id: Optional[int] = None
    name: str
    desc: str
    permissions: List[int]

    @field_validator("name")
    def validate_name (cls, v):
        """验证角色名称"""
        if v is None or v == "":
            raise ValidationException("角色名称不能为空")
        return v

    @field_validator("desc")
    def validate_desc (cls, v):
        """验证角色描述"""
        if v is None or v == "":
            raise ValidationException("角色描述不能为空")
        return v

    @field_validator("permissions")
    def validate_permission (cls, v):
        """验证角色权限"""
        if v is None or len(v) == 0:
            raise ValidationException("角色权限不能为空")
        return v


# 序列化角色数据
class RoleSerialize(BaseModel):
    id: int
    name: str
    desc: str
    permissions: List[int]
    created_at: str
    permission_list: Optional[List[Dict[str, Any]]] =None

    @classmethod
    async def from_orm (cls, obj: RoleModel):
        # 提取权限列表并转换为整数列表
        permission_lists = [int(x) for x in obj.permissions.split(",")]
        return cls(
            id = obj.id,
            name = obj.name,
            desc = obj.desc,
            permissions = permission_lists,
            created_at = format_datetime(obj.created_at),
            permission_list = None
        )
    model_config = ConfigDict(from_attributes=True)

class PermissionTree:
    """
    菜单权限数据序列化
    """

    @classmethod
    async def from_orm (cls, data_list):
        top_level = find_children(data_list, 0)
        # 递归构建整个树型选择结构
        return [PermissionTree.permission_tree(obj, data_list) for obj in top_level]

    @staticmethod
    def permission_tree (data, data_list):
        tree = {
            "label": data.label,
            "key": data.id,
            "types": data.types
        }
        children = [
            PermissionTree.permission_tree(child, data_list) for child in find_children(data_list, data.id)
        ]
        if children:
            tree["children"] = children
        return tree